<template>
  <div class="login-page">
    <div class="account-view">
      <n-form
        ref="loginForm"
        :model="submitForm"
        :rules="rules"
        label-placement="left"
      >
        <n-form-item
          label="账号"
          path="userName"
        >
          <n-input
            v-model:value="submitForm.userName"
            placeholder="请输入登录账号"
          />
        </n-form-item>
        <n-form-item
          label="密码"
          path="password"
        >
          <n-input
            v-model:value="submitForm.password"
            type="password"
            placeholder="请输入登录密码"
          />
        </n-form-item>
        <n-form-item>
          <n-button
            type="primary"
            block
            @click="handleSubmit"
          >
            登 录
          </n-button>
        </n-form-item>
      </n-form>
    </div>
  </div>
</template>

<script lang="ts" setup name="Login">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { FormRules, FormValidationError, useMessage } from 'naive-ui'
import { useUserStore } from '@/store/modules/user'

// 表单实例
const loginForm = ref()

const message = useMessage()
const router = useRouter()

// 登录表单
const submitForm = reactive({
  userName: 'admin',
  password: '111111'
})
// 表单验证规则
const rules: FormRules = {
  userName: { required: true, message: '请输入用户名', trigger: 'blur' },
  password: { required: true, message: '请输入密码', trigger: 'blur' }
}

// 登录提交
const handleSubmit = (e: MouseEvent) => {
  e.preventDefault()
  loginForm.value?.validate(async(errors: Array<FormValidationError>) => {
    if (errors) {
      message.error('请填写完整信息，并且进行验证码校验')
    } else {
      await useUserStore().login(submitForm)
      message.success('登录成功', {
        onAfterLeave: () => {
          router.replace('/')
        }
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.login-page {
  height: 100%;
  background-color: #f1f1f1;
  display: flex;
  justify-content: center;
  align-items: center;

  .account-view {
    width: 400px;
    background-color: #fff;
    padding: 30px;
    border-radius: 10px;
  }
}
</style>
